module namespace search = "http://www.xmlproject.com/smi/lib/controller/search";

import module namespace rest = "http://expath.org/ns/http-client";
import module namespace json = "http://www.zorba-xquery.com/modules/json";
import module namespace base64 = "http://www.zorba-xquery.com/modules/base64";
import module namespace html = "http://www.zorba-xquery.com/modules/tidy";
import module namespace util = "http://www.zorba-xquery.com/zorba/util-functions";

declare namespace youNS="http://www.w3.org/2005/Atom";

(:~
 : this function gets search results for the given query string from ebay.
 : It returns an xml representation of the search results.
 $vq = search
 $s = viewcount;
 $i max results
 $o start index

http://gdata.youtube.com/feeds/api/videos?q={$vq}&orderby={$s}&max-results={$i}&start-index={$o}
https://gdata.youtube.com/feeds/api/videos?q=$query&orderby=viewCount&start-index=1&max-results=5&v=2
 
 : @param $query the plain unencoded search term to search for
 : @return returns a searchresult element containing the provider name and results
 :)
declare sequential function search:youtube($query as xs:string)
{
    let $searchstring := fn:encode-for-uri($query)
    let $youtubeURL := "http://gdata.youtube.com/feeds/api/videos?q="
    let $youtubeURL := fn:concat($youtubeURL, $searchstring)
    let $youtubeURL2 := "&amp;orderby=viewCount&amp;start-index=1&amp;max-results=5&amp;v=2"
    let $youtubeURL := fn:concat($youtubeURL, $youtubeURL2)
  (: prepare the search url :)
  
  return 
    <searchresult>
            <provider>Youtube</provider>
            {
            (:string(doc("2youtube.xml")//entry/link[@rel = "alternate"]/@href):)
                let $hits := rest:send-request((), $youtubeURL)[2]
                for $hit in $hits//youNS:entry
                
                    let $title := string($hit//youNS:title)
                    let $href := string($hit//youNS:link[@rel = "alternate"]/@href)
                    let $content := string($hit//youNS:link[@rel = "alternate"]/@href)
                    let $rating := string($hit//youNS:link[@rel = "alternate"]/@href)
                    let $views := string($hit//youNS:link[@rel = "alternate"]/@href)
                    (: we use tidy to remove the encoded html tags (e.g. &lt;) in the google contents :)
                    let $content := html:tidy($href)
                return <result title="{$title}" href="{$href}">{$content}</result>
            }
        </searchresult>
};